import * as THREE from "three";

/**
 * 基础地图层类
 */
export class BaseMapLayer {
  constructor(scene, projection, textureLoader) {
    this.scene = scene;
    this.projection = projection;
    this.textureLoader = textureLoader;
    this.mapObject = new THREE.Object3D(); // 地图对象容器

    // 预加载纹理
    this.matcapTexture = this.textureLoader.load(
      "./model_assets/C7C7D7_4C4E5A_818393_6C6C74-512px.png"
    );
  }

  /**
   * 从GeoJSON数据创建地图
   * @param {Object} jsonData GeoJSON数据
   */
  createFromGeoJson(jsonData) {
    if (!jsonData || !jsonData.features) return;

    const features = jsonData.features;

    features.forEach((feature) => {
      // 单个省份
      const province = new THREE.Object3D();

      // 数据整合
      province.properties = feature.properties.name;
      const coordinates = feature.geometry.coordinates;

      // 多个多边形
      if (feature.geometry.type === "MultiPolygon") {
        coordinates.forEach((coordinate) => {
          coordinate.forEach((rows) => {
            const mesh = this.drawExtrudeMesh(rows);
            province.add(mesh);
          });
        });
      }

      // 单个多边形
      if (feature.geometry.type === "Polygon") {
        coordinates.forEach((coordinate) => {
          const mesh = this.drawExtrudeMesh(coordinate);
          province.add(mesh);
        });
      }

      this.mapObject.add(province);
    });

    // 将地图对象添加到场景
    this.scene.add(this.mapObject);
  }

  /**
   * 绘制立体几何
   * @param {Array} polygon 多边形点数组
   * @returns {THREE.Mesh} 网格对象
   */
  drawExtrudeMesh(polygon) {
    const shape = new THREE.Shape();

    polygon.forEach((row, i) => {
      const [x, y] = this.projection(row);

      if (i === 0) {
        shape.moveTo(x, -y);
      }
      shape.lineTo(x, -y);
    });

    // 挤压缓冲几何 - 基础层高度为0.3
    const geometry = new THREE.ExtrudeGeometry(shape, {
      depth: 0.3,
      bevelEnabled: false,
    });

    const material = new THREE.MeshMatcapMaterial({
      matcap: this.matcapTexture,
    });

    return new THREE.Mesh(geometry, material);
  }

  /**
   * 清理资源
   */
  dispose() {
    if (this.mapObject) {
      this.scene.remove(this.mapObject);

      // 递归遍历所有子对象并释放几何体和材质
      this.mapObject.traverse((obj) => {
        if (obj.isMesh) {
          if (obj.geometry) obj.geometry.dispose();
          if (obj.material) {
            if (Array.isArray(obj.material)) {
              obj.material.forEach((mat) => mat.dispose());
            } else {
              obj.material.dispose();
            }
          }
        }
      });
    }
  }
}
